package com.hunray.rent.security;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

import com.hunray.rent.entity.User;

public class PasswordHelper {
	private static RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();

	public static Properties getProperties() {
		Properties properties = new Properties();
		InputStream in = ClassLoader
				.getSystemResourceAsStream("application.properties");
		try {
			properties.load(in);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return properties;
	}

	public static String getAlgorithmName() {
		return PasswordHelper.getProperties().getProperty("hashAlgorithmName");
	}

	public static int getHashIterations() {
		return Integer.parseInt(PasswordHelper.getProperties().getProperty(
				"hashIterations"));
	}

	public static void encryptPassword(User user) {
		user.setSalt(randomNumberGenerator.nextBytes().toHex());

		String newPassword = new SimpleHash(PasswordHelper.getAlgorithmName(),
				user.getPassword(), ByteSource.Util.bytes(user.getSalt()),
				PasswordHelper.getHashIterations()).toHex();
		user.setPassword(newPassword);
	}
}
